<template>
  <div>
    <el-dialog
      :visible.sync="visible"
      title="逻辑设置"
      width="80%"
      :before-close="handleClose"
    >
      <!-- 逻辑表单 -->
      <el-form
        :model="logicSetUpForm"
        :rules="logicSetUpFormRules"
        ref="logicSetUpFormRef"
        label-width="90px"
        label-position="left"
      >
        <el-form-item label="逻辑类型" prop="logic_type">
          <el-select
            v-model="logicSetUpForm.logic_type"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              key="1"
              label="显示逻辑"
              :value="typeof logicSetUpForm.logic_type == 'string' ? '1' : 1"
            >
            </el-option>
            <el-option
              key="2"
              label="跳转逻辑"
              :value="typeof logicSetUpForm.logic_type == 'string' ? '2' : 2"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设置条件" required>
          <el-row :gutter="10" v-show="logicSetUpForm.logic_type == 1">
            <el-col style="width: 66px">符合以下</el-col>
            <el-col style="width: 90px">
              <el-form-item prop="logic_condition">
                <el-select
                  v-model="logicSetUpForm.logic_condition"
                  placeholder="请选择"
                  filterable
                >
                  <el-option
                    key="1"
                    label="全部"
                    :value="
                      typeof logicSetUpForm.logic_condition == 'string'
                        ? '1'
                        : 1
                    "
                  >
                  </el-option>
                  <el-option
                    key="2"
                    label="任一"
                    :value="
                      typeof logicSetUpForm.logic_condition == 'string'
                        ? '2'
                        : 2
                    "
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col style="width: 136px">条件时显示此问题：</el-col>
          </el-row>
          <el-button
            class="theme-background-color"
            icon="el-icon-plus"
            size="mini"
            v-show="
              logicSetUpForm.logic_type == 1 &&
              conditionForm.conditionTableData.length == 0
            "
            @click="addCondition"
            >增加条件</el-button
          >
          <el-row
            v-show="
              logicSetUpForm.logic_type == 1 &&
              conditionForm.conditionTableData.length != 0
            "
          >
            <el-form
              ref="conditionFormRef"
              :model="conditionForm"
              :rules="conditionFormRules"
              style="width: 100%; margin: 0"
            >
              <el-table
                :data="conditionForm.conditionTableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                :show-header="false"
              >
                <el-table-column>
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="
                        'conditionTableData.' + scope.$index + '.question_id'
                      "
                      :rules="conditionFormRules.question_id"
                    >
                      <el-select
                        v-model="scope.row.question_id"
                        placeholder="请选择问题"
                        filterable
                        clearable
                        @change="getOptions(scope.row)"
                      >
                        <el-option
                          v-for="(item, index) in questionBefore"
                          :key="index"
                          :label="index + 1 + '.' + item.title"
                          :value="
                            typeof scope.row.question_id == 'string'
                              ? item.id + ''
                              : item.id
                          "
                        >
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column>
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="
                        'conditionTableData.' +
                        scope.$index +
                        '.select_condition'
                      "
                      :rules="
                        scope.row.question_id != ''
                          ? [
                              {
                                required: true,
                                message: '请选择',
                                trigger: 'change'
                              }
                            ]
                          : []
                      "
                    >
                      <el-select
                        v-model="scope.row.select_condition"
                        placeholder="请选择"
                        filterable
                        clearable
                        @change="$forceUpdate()"
                      >
                        <el-option
                          v-for="(item, index) in scope.row.conditionOptions"
                          :key="index"
                          :label="item.name"
                          :value="
                            typeof scope.row.select_condition == 'string'
                              ? item.id + ''
                              : item.id
                          "
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column>
                  <template slot-scope="scope">
                    <el-row v-show="scope.row.select_condition == 3">
                      <el-col :span="9">
                        <el-form-item
                          :prop="
                            'conditionTableData.' +
                            scope.$index +
                            '.special_option'
                          "
                          :rules="
                            scope.row.select_condition == 3
                              ? [
                                  {
                                    required: true,
                                    message: '请选择',
                                    trigger: 'change'
                                  }
                                ]
                              : []
                          "
                        >
                          <el-select
                            v-model="scope.row.special_option"
                            placeholder="请选择"
                            filterable
                            clearable
                          >
                            <el-option
                              key="1"
                              label="数字"
                              :value="
                                typeof scope.row.special_option == 'string'
                                  ? '1'
                                  : 1
                              "
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="7">
                        <el-form-item
                          :prop="
                            'conditionTableData.' +
                            scope.$index +
                            '.range_start'
                          "
                          :rules="
                            scope.row.special_option == 1
                              ? [
                                  {
                                    required: true,
                                    message: '请选择',
                                    trigger: 'change'
                                  },
                                  {
                                    type: 'number',
                                    message: '必须为数字值'
                                  }
                                ]
                              : []
                          "
                        >
                          <el-input
                            placeholder="请输入范围"
                            v-model.number="scope.row.range_start"
                            oninput="value=value.replace(/\D/g,'')"
                          >
                            ></el-input
                          >
                        </el-form-item>
                      </el-col>
                      <el-col class="line" :span="1">-</el-col>
                      <el-col :span="7">
                        <el-form-item
                          :prop="
                            'conditionTableData.' + scope.$index + '.range_end'
                          "
                          :rules="
                            scope.row.special_option == 1
                              ? [
                                  {
                                    required: true,
                                    message: '请选择',
                                    trigger: 'change'
                                  },
                                  {
                                    type: 'number',
                                    message: '必须为数字值'
                                  }
                                ]
                              : []
                          "
                        >
                          <el-input
                            placeholder="请输入范围"
                            v-model.number="scope.row.range_end"
                            oninput="value=value.replace(/\D/g,'')"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-form-item
                      :prop="
                        'conditionTableData.' + scope.$index + '.select_option'
                      "
                      v-show="
                        scope.row.type != 3 &&
                        (scope.row.select_condition == 1 ||
                          scope.row.select_condition == 2)
                      "
                      :rules="
                        scope.row.type != 3 &&
                        (scope.row.select_condition == 1 ||
                          scope.row.select_condition == 2)
                          ? [
                              {
                                required: true,
                                message: '请选择',
                                trigger: 'change'
                              }
                            ]
                          : []
                      "
                    >
                      <el-select
                        v-model="scope.row.select_option"
                        placeholder="请选择"
                        filterable
                        clearable
                        :multiple="scope.row.type == 2"
                        collapse-tags
                        v-if="update"
                        @change="optionChange(scope.row)"
                      >
                        <el-option
                          v-for="(item, index) in scope.row.optionArr"
                          :key="index"
                          :label="item.content"
                          :value="
                            typeof scope.row.select_option == 'string'
                              ? item.id + ''
                              : item.id
                          "
                        >
                        </el-option>
                        <el-option label="任意选项" value="any"></el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column width="100px">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      @click="
                        deleteCondition(
                          scope.$index,
                          conditionForm.conditionTableData
                        )
                      "
                      >删除</el-button
                    >
                    <el-button
                      type="text"
                      @click="addCondition(scope.row.index)"
                      >增加</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </el-row>

          <el-button
            class="theme-background-color"
            icon="el-icon-plus"
            size="mini"
            v-show="
              logicSetUpForm.logic_type == 2 &&
              jumpConditionForm.jumpConditionTableData.length == 0
            "
            >增加条件</el-button
          >
          <el-row
            v-show="
              logicSetUpForm.logic_type == 2 &&
              jumpConditionForm.jumpConditionTableData.length != 0
            "
          >
            <el-form
              ref="jumpConditionFormRef"
              :model="jumpConditionForm"
              :rules="jumpConditionFormRules"
              style="width: 100%; margin: 0"
            >
              <el-table
                :data="jumpConditionForm.jumpConditionTableData"
                style="width: 100%"
                :row-class-name="tableRowClassName"
                :show-header="false"
              >
                <el-table-column width="100px">如果本题选中</el-table-column>
                <el-table-column>
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="
                        'jumpConditionTableData.' +
                        scope.$index +
                        '.select_option'
                      "
                      :rules="jumpConditionFormRules.select_option"
                    >
                      <el-select
                        v-model="scope.row.select_option"
                        placeholder="请选择选项"
                        filterable
                        clearable
                        :multiple="questionType == 2"
                        collapse-tags
                        v-if="update"
                        @change="optionChange(scope.row)"
                      >
                        <el-option
                          v-for="(item, index) in questionOptions"
                          :key="index"
                          :label="item.content"
                          :value="
                            typeof scope.row.select_option == 'string'
                              ? item.id + ''
                              : item.id
                          "
                        >
                        </el-option>
                        <el-option
                          label="显示"
                          value="show"
                          v-if="questionType == 3"
                        ></el-option>
                        <el-option
                          label="任意选项"
                          value="any"
                          v-else
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column width="70px">则跳转到</el-table-column>
                <el-table-column>
                  <template slot-scope="scope">
                    <el-form-item
                      :prop="'jumpConditionTableData.' + scope.$index + '.jump'"
                      :rules="jumpConditionFormRules.jump"
                    >
                      <el-select
                        v-model="scope.row.jump"
                        placeholder="请选择问题"
                        filterable
                        clearable
                      >
                        <el-option
                          v-for="(item, index) in questionAfter"
                          :key="index"
                          :label="index + sortNow + 2 + '.' + item.title"
                          :value="
                            typeof scope.row.jump == 'string'
                              ? item.id + ''
                              : item.id
                          "
                        >
                        </el-option>
                        <el-option
                          label="正常结束（计入结果）"
                          value="end"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column width="100px">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      @click="
                        deleteCondition(
                          scope.$index,
                          jumpConditionForm.jumpConditionTableData
                        )
                      "
                      >删除</el-button
                    >
                    <el-button
                      type="text"
                      @click="addConditionJump(scope.row.index)"
                      >增加</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </el-row>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button class="theme-background-color" @click="saveLogicInfo"
          >保 存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    logicSetUpDialogVisible: {
      type: Boolean,
      default: function () {
        return {}
      }
    },
    questionIdNow: {
      type: Number,
      default: function () {
        return {}
      }
    },
    // 所有的问题数据
    questionInfo: {
      type: Array,
      default: function () {
        return {}
      }
    },
    logicObject: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  data() {
    return {
      visible: this.logicSetUpDialogVisible,
      questionType: '',

      logicSetUpForm: {
        logic_type: '1',
        logic_condition: '1',
        logic_data: []
      },
      logicSetUpFormRules: {
        logic_type: [{ required: true, message: '请选择', trigger: 'change' }],
        logic_condition: [
          { required: true, message: '请选择', trigger: 'change' }
        ]
      },

      conditionForm: { conditionTableData: [{ id: '' }] },
      conditionFormRules: {
        question_id: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      questionBefore: [],
      update: true, // 控制多选变化时不渲染组件，计算完再渲染组件
      selectChange: '',

      jumpConditionForm: {
        jumpConditionTableData: [{ id: '' }]
      },
      jumpConditionFormRules: {
        select_option: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        jump: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      questionAfter: [],
      questionOptions: [],
      sortNow: ''
    }
  },
  created() {
    if (this.logicSetUpDialogVisible) {
      this.displayRequiredData()
    }
    console.log(this.questionIdNow, this.logicSetUpDialogVisible)
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          this.$refs.logicSetUpFormRef.resetFields()
          this.$emit('update:logicSetUpDialogVisible', false)
          done()
        })
        .catch((_) => {})
    },
    tableRowClassName({ row, rowIndex }) {
      //   把每一行的索引放进row
      row.index = rowIndex
    },
    deleteCondition(index, data) {
      // this.conditionForm.conditionTableData.splice(row.index, 1)
      data.splice(index, 1)
    },
    addCondition(index) {
      if (!this.validateField('conditionFormRef')) {
        return
      }
      this.conditionForm.conditionTableData.splice(index + 1, 0, {
        id: '',
        question_id: '',
        select_condition: '',
        special_option: '',
        range_start: '',
        range_end: '',
        select_option: ''
      })
    },
    addConditionJump(index) {
      if (!this.validateField('jumpConditionFormRef')) {
        return
      }
      this.jumpConditionForm.jumpConditionTableData.splice(index + 1, 0, {
        id: '',
        select_option: '',
        jump: '',
        type: this.questionType
      })
    },
    optionChange(row) {
      this.$forceUpdate()
      console.log(row.select_option)
      // 多选题
      if (row.type == 2) {
        let len = row.select_option.length
        // 选择了多个选项，且最后一个选项是任意选项
        if (len > 1 && row.select_option[len - 1] == 'any') {
          // 取消其他选项的选中状态
          row.select_option = ['any']
        } else if (len == 2 && row.select_option[0] == 'any') {
          // 当选了两个选项的时候，如果第一个选项是任意选项，则取消任意选项的选中状态
          row.select_option.shift()
        }
      }
    },
    closeDialog() {
      this.$emit('update:logicSetUpDialogVisible', false)
    },
    // 对部分表单字段进行校验
    validateField(form, index = '') {
      let result = true
      for (let item of this.$refs[form].fields) {
        // if (item.prop.split('.')[1] == index) {
        this.$refs[form].validateField(item.prop, (error) => {
          // console.log(item.prop, error)
          if (error != '' && error != undefined) {
            result = false
          }
        })
        // }
        if (!result) break
      }
      return result
    },
    checkShowDuplicates() {
      const data = this.conditionForm.conditionTableData
      let tempArray = []
      for (let index = 0; index < data.length; index++) {
        for (let j = 0; j < tempArray.length; j++) {
          if (data[index].question_id == tempArray[j].question_id) {
            if (data[index].select_condition == tempArray[j].select_condition) {
              if (data[index].type == 1) {
                if (data[index].select_option == tempArray[j].select_option) {
                  return index
                }
              } else if (data[index].type == 2) {
                // 多选题
                console.log(data[index].select_option)
                // 得先排序再转字符串再比较
                if (
                  data[index].select_option.sort().toString() ==
                  tempArray[j].select_option.sort().toString()
                ) {
                  return index
                }
              } else {
                // 问答题
                return index
              }
            }
          }
        }
        tempArray.push(data[index])
      }
      for (let i = 0; i < data.length; i++) {
        let option_temp = data[i].select_option
        if (Array.isArray(option_temp)) {
          option_temp = option_temp.join(',')
          data[i].select_option = option_temp
        }
      }
      return ''
    },
    checkJumpDuplicates() {
      const data = this.jumpConditionForm.jumpConditionTableData
      let tempArray = []
      for (let index = 0; index < data.length; index++) {
        console.log(tempArray, data[index])
        for (let j = 0; j < tempArray.length; j++) {
          if (data[index].type == 2) {
            // 多选题
            if (
              data[index].select_option.sort().toString() ==
              tempArray[j].select_option.sort().toString()
            ) {
              return index
            }
          } else {
            if (data[index].select_option == tempArray[j].select_option) {
              return index
            }
          }
        }
        tempArray.push(data[index])
      }
      return ''
    },
    saveLogicInfo() {
      this.$refs.logicSetUpFormRef.validate(async (valid) => {
        if (!valid) return
        console.log(this.logicSetUpForm)

        if (this.logicSetUpForm.logic_type == 1) {
          if (!this.validateField('conditionFormRef')) {
            return
          }
          console.log(this.conditionForm)
          // 校验重复项
          const line = this.checkShowDuplicates()
          console.log(line)
          if (line) {
            return this.$message.error('第' + (line + 1) + '行为重复项')
          }

          this.logicSetUpForm.logic_data = this.conditionForm.conditionTableData
        } else {
          if (!this.validateField('jumpConditionFormRef')) {
            return
          }
          console.log(this.jumpConditionForm)
          // 校验重复项
          const line = this.checkJumpDuplicates()
          console.log(line)
          if (line) {
            return this.$message.error('第' + (line + 1) + '行为重复项')
          }

          this.logicSetUpForm.logic_data =
            this.jumpConditionForm.jumpConditionTableData
        }
        // const { data: res } = await this.$http.post(
        //   '/admin/question_manage/logicSet',
        //   this.logicSetUpForm
        // )
        // if (res.meta.status == 200) {
        //   return this.$message.error(res.meta.msg)
        // }
        this.$emit('showLogicData', this.logicSetUpForm)
        this.visible = false
        this.$emit('update:logicSetUpDialogVisible', false)
      })
    },
    displayRequiredData() {
      this.sortNow = ''
      for (let i = 0; i < this.questionInfo.length; i++) {
        // 当前问题类型
        if (this.questionIdNow == this.questionInfo[i].id) {
          this.questionType = this.questionInfo[i].type
          this.questionOptions = this.questionInfo[i].option_data
          this.sortNow = i
          break
        }
      }
      this.questionBefore = []
      this.questionAfter = []
      for (let i = 0; i < this.questionInfo.length; i++) {
        // 当前问题之前的问题（显示逻辑）
        if (i < this.sortNow) {
          this.questionBefore.push(this.questionInfo[i])
        } else if (i > this.sortNow) {
          // 当前问题之后的问题（跳转逻辑）
          this.questionAfter.push(this.questionInfo[i])
        }
      }
      console.log(this.questionInfo, this.questionIdNow)
      console.log(this.questionBefore, this.questionAfter)

      // this.addCondition()
      // this.addConditionJump()
    },
    selectDataById(id) {
      for (let i = 0; i < this.questionInfo.length; i++) {
        if (id == this.questionInfo[i].id) {
          return this.questionInfo[i]
        }
      }
    },
    getOptions(row) {
      this.$set(row, 'select_option', [])
      this.handleChangeData(row)
    },
    handleChangeData(row) {
      const data = this.selectDataById(row.question_id)
      this.selectChange = data.type
      if (data.type == 3) {
        row.conditionOptions = [
          { id: 1, name: '显示' },
          { id: 2, name: '未显示' },
          { id: 3, name: '范围' }
        ]
      } else {
        row.conditionOptions = [
          { id: 1, name: '选中' },
          { id: 2, name: '未选中' }
        ]

        row.optionArr = data.option_data
      }
      row.type = data.type
    },
    editData() {
      console.log(this.logicObject)
      if (JSON.stringify(this.logicObject) != '{}') {
        for (const item in this.logicSetUpForm) {
          this.logicSetUpForm[item] = this.logicObject[item]
        }
        let logic_data = JSON.parse(JSON.stringify(this.logicObject.logic_data))
        for (let i = 0; i < logic_data.length; i++) {
          const data = []
          if (this.logicObject.logic_type == 1) {
            data = this.selectDataById(logic_data[i].question_id)
          } else {
            if (logic_data[i].jump != 'end') {
              data = this.selectDataById(logic_data[i].jump)
            }
          }
          let select_option = logic_data[i].select_option

          console.log(data)
          if (data.type == 2) {
            console.log(select_option)
            select_option = (select_option + '').split(',')
            for (let k = 0; k < select_option.length; k++) {
              select_option[k] = parseInt(select_option[k])
            }
            logic_data[i].select_option = select_option
          }
        }
        if (this.logicObject.logic_type == 1) {
          this.conditionForm.conditionTableData = logic_data
          for (
            let i = 0;
            i < this.conditionForm.conditionTableData.length;
            i++
          ) {
            this.handleChangeData(this.conditionForm.conditionTableData[i])
          }
          console.log(this.conditionForm.conditionTableData)
        } else {
          this.jumpConditionForm.jumpConditionTableData = logic_data
        }
      }
    }
  },
  watch: {
    logicSetUpDialogVisible() {
      this.visible = this.logicSetUpDialogVisible
      if (this.visible) {
        this.displayRequiredData()
        // 编辑
        this.editData()
      } else {
        this.$refs.logicSetUpFormRef.resetFields()

        this.conditionForm.conditionTableData = [{ id: '' }]
        this.jumpConditionForm.jumpConditionTableData = [{ id: '' }]
      }
    },
    selectChange() {
      this.update = false
      setTimeout(() => {
        this.update = true
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  margin: 0px 15px;
  .el-select {
    width: 100%;
  }
}
.line {
  text-align: center;
  line-height: 40px;
}
/deep/.el-dialog__footer {
  text-align: center;
  .el-button {
    width: 160px;
  }
}
</style>
